package com.lupan.mutithred.cp6_CompletionService;

import java.util.concurrent.*;

/**
 * 说明：
 *
 * @author lupan
 * @version 2017/5/8 14:01
 */
public class Main {

    public static class Task implements Callable<String> {

        private long sleepValue;
        private String name;

        public Task(long sleepValue, String name) {
            this.sleepValue = sleepValue;
            this.name = name;
        }

        @Override
        public String call() throws Exception {
            System.out.println(name + "开始");
            Thread.currentThread().sleep(sleepValue);
            System.out.println(name + "结束");
            return "完成任务" + name;
        }
    }


    public static void main(String[] args) throws InterruptedException, ExecutionException {

        Task task1 = new Task(5000,"task1");
        Task task2 = new Task(2000,"task2");
        Task task3 = new Task(3000,"task3");
        Task task4 = new Task(4000,"task4");

        Executor pool = new ThreadPoolExecutor(5,10,1000, TimeUnit.SECONDS, new LinkedBlockingDeque<>());
        CompletionService<String> cs = new ExecutorCompletionService<String>(pool);

        cs.submit(task1);
        cs.submit(task2);
        cs.submit(task3);
        cs.submit(task4);

        for (int i = 0; i < 4; i++) {
            System.out.println(cs.take().get());
        }
    }
}
